<?php
namespace Admin\Model;
use Think\Model;

class PermitModel extends Model{
	//查询总记录（主权限）
	public function total(){
		$total = $this->query("SELECT COUNT(*) count FROM `".C('DB_PREFIX')."permit` WHERE `sid`=0 AND (`name` LIKE '%".I('get.keyword')."%' OR `c` LIKE '%".I('get.keyword')."%' OR `a` LIKE '%".I('get.keyword')."%' OR `id` IN (SELECT `sid` FROM `".C('DB_PREFIX')."permit` WHERE `name` LIKE '%".I('get.keyword')."%' OR `c` LIKE '%".I('get.keyword')."%' OR `a` LIKE '%".I('get.keyword')."%'))");
		return $total[0]['count'];
	}
	
	//查询所有（主权限）
	public function all($firstRow){
		return $this->query("SELECT `id`,`name`,`c`,`a`,`selected`,`sid`,`sort` FROM `".C('DB_PREFIX')."permit` WHERE `sid`=0 AND (`name` LIKE '%".I('get.keyword')."%' OR `c` LIKE '%".I('get.keyword')."%' OR `a` LIKE '%".I('get.keyword')."%' OR `id` IN (SELECT `sid` FROM `".C('DB_PREFIX')."permit` WHERE `name` LIKE '%".I('get.keyword')."%' OR `c` LIKE '%".I('get.keyword')."%' OR `a` LIKE '%".I('get.keyword')."%')) ORDER BY `sort` ASC LIMIT $firstRow,".C('PAGE_SIZE'));
	}
	
	//查询所有（主权限，不分页）
	public function all2(){
		$map['sid'] = 0;
		return $this->field('id,name,c,a')
					->where($map)
					->order(array('sort'=>'ASC'))
					->select();
	}
	
	//查询所有（子权限）
	public function all3($sid){
		$map = array(
			'_complex'=>array(
				'name'=>array('like','%'.I('get.keyword').'%'),
				'c'=>array('like','%'.I('get.keyword').'%'),
				'a'=>array('like','%'.I('get.keyword').'%'),
				'_logic'=>'OR'
			),
			'sid'=>$sid
		);
		return $this->field('id,name,c,a,selected,sort')
					->where($map)
					->order(array('sort'=>'ASC'))
					->select();
	}
	
	//查询所有（默认权限）
	public function all4(){
		$map['selected'] = 1;
		return $this->field('id')
					->where($map)
					->order(array('id'=>'ASC'))
					->select();
	}
	
	//查询一条
	public function one(){
		$map['id'] = I('get.id');
		return $this->field('selected')->where($map)->find();
	}
	
	//设置和取消默认
	public function selected($selected){
		$data = array(
			'id'=>I('get.id'),
			'selected'=>$selected
		);
		return $this->save($data);
	}
	
	//排序
	public function sort($id,$sort){
		$data = array(
			'id'=>$id,
			'sort'=>$sort
		);
		return $this->save($data);
	}
}